//
//  HEFaceAuthManage.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/19.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEFaceAuthManage.h"
#include <mach/mach_time.h>
#import <objc/runtime.h>
#import <AssetsLibrary/AssetsLibrary.h>
//#import <WBOCRService/WBOCRService.h>


@interface HEFaceAuthManage ()

@property (nonatomic, copy) NSString *appid;
@property (nonatomic, copy) NSString *nonce;
@property (nonatomic, copy) NSString *sign;
@property (nonatomic, copy) NSString *orderNO;
@property (nonatomic, copy) NSString *userID;
@property (nonatomic, copy) NSString *wbfacebaseURLString;
@property (nonatomic, copy) NSString *wbgetFaceIDURLString;
@property (nonatomic, strong) UIImage *sourceImage;


@property (nonatomic, copy) NSString *LICENCE;
@property (nonatomic, copy) NSString *appID;

@end

@implementation HEFaceAuthManage

+ (instancetype)sharedClient {
    static HEFaceAuthManage *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[HEFaceAuthManage alloc] init];
    });
    return _sharedClient;
}

//
//#pragma mark -
//- (void)startServiceWithType:(WBFaceVerifyLivingType)type {
//    NSLog(@"start!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
//    //生产都是: https://ida.webank.com      APPID是: TIDA0001
////    self.userID = [NSString stringWithFormat:@"userID%llu", mach_absolute_time()];
//    self.userID = [UserManager sharedUserManager].curUserInfo.id;
//
//    self.wbgetFaceIDURLString = @"https://idasc.webank.com/api/server/getfaceid";
//    self.orderNO = [DYTools createUuid];
//    
//    // 测试
////    self.appid = @"TIDAQrFk";
////    self.LICENCE = @"N+RTcoohAUJTxGa505RXhUMWmKEOp8ehmTn58TcR8RDTOWl1MHNmPtM6YVnqxB0r+JXY4Th8sEs1DM4ARosx2eoJ8TVTtB1sNcsgz0hD90MzIiHkN6jVyUZc5Wg3tKzMIeDk2U6s2yXjD0//C8cDjY4f5qWFs8uNwTVRHYwwLKoVeLix9ZqGAXJg/Uf2HN7M7oaBkNDu0KRLhyTkbGi+prnPV7jKek4xsXFtAdec9y0lHMmp0Owh1NNvwdrO30Oehj+veDpOAIwG2iMIQYhl3PmktJPyRsdi0G9fKeCw5ZFz8AEuJ671n4PCJIx10rMDG/Zl3BU3LYhJePVCVTutzA==";
//    
//    // 正式
//    self.appid = @"IDAZYz7E";
//    self.LICENCE = @"N+RTcoohAUJTxGa505RXhUMWmKEOp8ehmTn58TcR8RDTOWl1MHNmPtM6YVnqxB0r+JXY4Th8sEs1DM4ARosx2eoJ8TVTtB1sNcsgz0hD90MzIiHkN6jVyUZc5Wg3tKzMIeDk2U6s2yXjD0//C8cDjY4f5qWFs8uNwTVRHYwwLKp9uabLXsuievZzv+IJDIbRBz3ReByiCUEM4GVIQSnGIV25+8gsQAOYgBcXSZhSP1ZaAyjHs9lpbWjDFXkNV7cEqjrnKwIxsYIFfx6AspzpP/kK9lb9FaukCCxX2PQlq9V6eHJd56z20bjTuRBVdWgQiXgdP77DyPL5XywbxLS8eg==";
//    
//
//    self.nonce = [DYTools createUuid];
//    self.sign = nil;
//
//    __weak typeof(self) weakSelf = self;
//    NSDictionary *params = @{@"appid":self.appid, @"id":self.userID,@"nonce":self.nonce};
//    
//    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KgetWeChatSign parameters:params success:^(id  _Nonnull responseObject) {
//        HEObjectDataResponse *response = [HEObjectDataResponse mj_objectWithKeyValues:responseObject];
//        weakSelf.sign = response.data;
//        if (weakSelf.sign == nil || [weakSelf.sign isKindOfClass:[NSNull class]]) {
//            [[Dialog Instance] hideHUD];
//            return ;
//        }else{
//#warning 这里是人脸识别的入口
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [weakSelf faceVerifyEntranceUsingFaceId:type];
//            });
//        }
//    } failure:^(NSError * _Nonnull error) {
//    }];
//}
//
//
//#pragma mark - WBFaceVerifyCustomerServiceDelegate
//
//
//- (UIImage *)base64StringToUIImage:(NSString *) base64String
//{
//
//    // 将base64字符串转为NSData
//    NSData *decodeData = [[NSData alloc]initWithBase64EncodedString:base64String options:(NSDataBase64DecodingIgnoreUnknownCharacters)];
//    // 将NSData转为UIImage
//    UIImage *decodedImage = [UIImage imageWithData: decodeData];
//    return decodedImage;
//}
//
//-(void)wbfaceVerifyCustomerServiceDidFinishedWithFaceVerifyResult:(WBFaceVerifyResult *)faceVerifyResult{
//    NSLog(@"result 结果: %@", faceVerifyResult);
// 
//    if (faceVerifyResult.isSuccess) {
//        
//    }else {
//        [Dialog toastBottom:@"人脸核身验证失败！"];
//    }
//    
//    if ([_delegate respondsToSelector:@selector(faceAuthResults:)]) {
//        [_delegate faceAuthResults: faceVerifyResult.isSuccess];
//    }
//}
//
//
//#pragma mark -
//
//- (WBFaceVerifySDKConfig *)getSDKSettings{
//    WBFaceVerifySDKConfig *config = [WBFaceVerifySDKConfig sdkConfig];
//    config.recordVideo = YES;
//    config.theme = WBFaceVerifyThemeLightness;
//    return  config;
//}
//
//// faceID版本接口. 动作活体和光线活体可以使用新接口
//-(void)faceVerifyEntranceUsingFaceId:(WBFaceVerifyLivingType)type{
//    
//    [WBFaceVerifyCustomerService sharedInstance].delegate = self;
//    WBFaceVerifySDKConfig *config = [self getSDKSettings];
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    BOOL usingSourceImage = [defaults boolForKey:@"settingHome_using_source_image"];
//    BOOL usingCompare = ![defaults boolForKey:@"settingHome_using_compare"];
//    BOOL isHDImage = ![defaults boolForKey:@"settingHome_hd_source_image"];
//    if (usingCompare) {
//        if(usingSourceImage) { //自带比对源接口
//            if (self.sourceImage == nil) {
////                [ISMessages showCardAlertWithTitle:@"获取faceid时, 参数出错" message:@"选择自带比对源, 但是未选择照片"
////                                          duration:3 hideOnSwipe:YES hideOnTap:YES alertType:ISAlertTypeInfo alertPosition:0 didHide:nil];
//                [[Dialog Instance] hideHUD];
//                return;
//            }
//
//            NSString *imageBase64Str = [self base64String:self.sourceImage];
//
//            //            NSDictionary *paramsBase = @{@"webankAppId":self.appid,
//            //                                     @"orderNo":self.orderNO,
//            //                                     @"userId":self.userID,
//            //                                     @"nonce":self.nonce,
//            //                                     @"version": @"1.0.0",
//            //                                     @"sign": self.sign,
//            //                                     @"sourcePhotoStr":imageBase64Str,
//            //                                     @"sourcePhotoType":isHDImage ?@"2":@"1",
//            //                                     };
//            // 自带比对源
//            NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
//            params[@"webankAppId"] = self.appid;
//            params[@"orderNo"] = self.orderNO;
//            params[@"userId"] = self.userID;
//            params[@"nonce"] = self.nonce;
//            params[@"version"] = @"1.0.0";
//            params[@"sign"] = self.sign;
//            params[@"sourcePhotoStr"] = imageBase64Str;
//            params[@"sourcePhotoType"] = isHDImage ?@"2":@"1";
//            params[@"name"] = _name;
//            params[@"idNo"] = _idNo;
//            NSData *bodydata = [NSJSONSerialization dataWithJSONObject:params options:NSJSONReadingMutableLeaves|NSJSONReadingAllowFragments error:nil];
//            NSURLSession *session = [NSURLSession sessionWithConfiguration:NSURLSessionConfiguration.defaultSessionConfiguration];
//            NSMutableURLRequest *requst = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.wbgetFaceIDURLString]];
//            [requst setTimeoutInterval:3];
//            [requst setHTTPMethod:@"POST"];
//            [requst setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//            requst.HTTPBody = bodydata;
//            NSLog(@"request: %@", requst);
//            NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:requst completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//                if (error != nil) {
//                    [[Dialog Instance] hideHUD];
//                    NSString *message = [NSString stringWithFormat:@"%@", error.description];
//                    NSLog(@"error: %@", error);
////                    [ISMessages showCardAlertWithTitle:@"获取faceID时, 请求返回error" message:message duration:10 hideOnSwipe:YES hideOnTap:YES alertType:ISAlertTypeInfo alertPosition:0 didHide:nil];
//                    return ;
//                }
//
//                NSError * jsonErr = nil;
//                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonErr];
//                if(jsonErr != nil){
//                    [[Dialog Instance] hideHUD];
//                    NSString *message = [NSString stringWithFormat:@"%@", jsonErr.description];
//                    NSLog(@"error: %@", error);
////                    [ISMessages showCardAlertWithTitle:@"获取faceID时, jsonErr返回error" message:message duration:10 hideOnSwipe:YES hideOnTap:YES alertType:ISAlertTypeInfo alertPosition:0 didHide:nil];
//                    return ;
//                }
//
//                //其他情况, json有数据, json没有faceId
//                NSLog(@"dict: %@", dict);
//                NSString *faceId = [dict valueForKeyPath:@"result.faceId"];
//                if (faceId.length <= 0) {
//                    [[Dialog Instance] hideHUD];
////                    [ISMessages showCardAlertWithTitle:@"获取faceID时, 后台没有返回faceId" message:dict.description duration:10 hideOnSwipe:YES hideOnTap:YES alertType:ISAlertTypeInfo alertPosition:0 didHide:nil];
//                    return ;
//                }
//
//                // 其他情况, 正常执行
//                // 活体检测 + 自带比对源
//                NSLog(@"正式开始启动!!!!!!!!!!!!!");
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [[WBFaceVerifyCustomerService sharedInstance] initSDKWithUserId:self.userID nonce:self.nonce sign:self.sign appid:self.appid orderNo:self.orderNO apiVersion:@"1.0.0" licence: self.LICENCE faceType:type faceId:faceId sdkConfig:config success:^{
//                        [[WBFaceVerifyCustomerService sharedInstance] startWbFaceVeirifySdk];
//                        [[Dialog Instance] hideHUD];
//
//                    } failure:^(WBFaceError * _Nonnull error) {
//                        [[Dialog Instance] hideHUD];
//                        if (kiOS8Later) {
//                            NSString *message = [NSString stringWithFormat:@"%@", error.desc];
//                            NSLog(@"error: %@", error);
////                            [ISMessages showCardAlertWithTitle:@"登录时候出错" message:message duration:10 hideOnSwipe:YES hideOnTap:YES alertType:ISAlertTypeInfo alertPosition:0 didHide:nil];
//                        }
//                    }];
//                });
//            }];
//
//            [dataTask resume];
//            return;
//        }else{
////            if (self.idTextField.text.length <= 0 || self.nameTextField.text.length <= 0) {
////                [ISMessages showCardAlertWithTitle:@"获取faceID时, 参数出错" message:@"姓名或者身份证出错" duration:10 hideOnSwipe:YES hideOnTap:YES alertType:ISAlertTypeInfo alertPosition:0 didHide:nil];
////                [[Dialog Instance] hideHUD];
////                return;
////            }
//            // 活体检测 + 身份证 + 姓名
//            NSDictionary *params = @{@"webankAppId":self.appid,
//                                     @"orderNo":self.orderNO,
//                                     @"name": _name,
//                                     @"idNo": _idNo,
//                                     @"userId":self.userID,
//                                     @"nonce":self.nonce,
//                                     @"version": @"1.0.0",
//                                     @"sign": self.sign,
//                                     };
//
//            NSData *bodydata = [NSJSONSerialization dataWithJSONObject:params options:NSJSONReadingMutableLeaves|NSJSONReadingAllowFragments error:nil];
//
//            NSURLSession *session = [NSURLSession sessionWithConfiguration:NSURLSessionConfiguration.defaultSessionConfiguration];
//            NSMutableURLRequest *requst = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.wbgetFaceIDURLString]];
//            [requst setHTTPMethod:@"POST"];
//            [requst setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//            requst.HTTPBody = bodydata;
//            NSLog(@"request: %@", requst);
//
//            NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:requst completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//
//                if (error != nil) {
//                    [[Dialog Instance] hideHUD];
//                    NSString *message = [NSString stringWithFormat:@"%@", error.description];
//                    NSLog(@"error: %@", error);
////                    [ISMessages showCardAlertWithTitle:@"获取faceID时, 请求返回error" message:message duration:10 hideOnSwipe:YES hideOnTap:YES alertType:ISAlertTypeInfo alertPosition:0 didHide:nil];
//                    return ;
//                }
//
//                NSError * jsonErr = nil;
//                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonErr];
//                if(jsonErr != nil){
//                    [[Dialog Instance] hideHUD];
//
//                    NSString *message = [NSString stringWithFormat:@"%@", jsonErr.description];
//                    NSLog(@"error: %@", error);
////                    [ISMessages showCardAlertWithTitle:@"获取faceID时, jsonErr返回error" message:message duration:10 hideOnSwipe:YES hideOnTap:YES alertType:ISAlertTypeInfo alertPosition:0 didHide:nil];
//                    return ;
//                }
//
//                //其他情况, json有数据, json没有faceId
//                NSLog(@"dict: %@", dict);
//                NSString *faceId = [dict valueForKeyPath:@"result.faceId"];
//                if (faceId.length <= 0) {
//                    [[Dialog Instance] hideHUD];
//
////                    [ISMessages showCardAlertWithTitle:@"获取faceID时, 后台没有返回faceId" message:dict.description duration:10 hideOnSwipe:YES hideOnTap:YES alertType:ISAlertTypeInfo alertPosition:0 didHide:nil];
//                    return ;
//                }
//
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    // 身份证+姓名接口
//                    NSString *name = _name;
//                    NSString *idNo = _idNo;
//                    WBFaceUserInfo *userInfo = [[WBFaceUserInfo alloc] init];
//                    userInfo.idType = @"01";
//                    userInfo.name = name;
//                    userInfo.idNo =idNo;
//
//                    //                    userInfo.name = _nameTextField.text.length > 0 ? _nameTextField.text : @"孟琬";
//                    //                    userInfo.idNo = _idTextField.text.length > 0 ? _idTextField.text : @"210203197503102721";
//                    [[WBFaceVerifyCustomerService sharedInstance] initSDKWithUserId:self.userID nonce:self.nonce sign:self.sign appid:self.appid orderNo:self.orderNO apiVersion:@"1.0.0" licence: self.LICENCE faceType:type faceId:faceId sdkConfig:config success:^{
//                        [[WBFaceVerifyCustomerService sharedInstance] startWbFaceVeirifySdk];
//                        [[Dialog Instance] hideHUD];
//
//                    } failure:^(WBFaceError * _Nonnull error) {
//                        [[Dialog Instance] hideHUD];
//                        if (kiOS8Later) {
//                            NSString *message = [NSString stringWithFormat:@"%@", error.desc];
//                            NSLog(@"error: %@", error);
////                            [ISMessages showCardAlertWithTitle:@"登录时候出错" message:message
////                                                      duration:10 hideOnSwipe:YES hideOnTap:YES alertType:ISAlertTypeInfo alertPosition:0 didHide:nil];
//                        }
//                    }];
//                });
//            }];
//
//            [dataTask resume];
//            return;
//        }
//    }else {// 不需要比对
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [[WBFaceVerifyCustomerService sharedInstance] initSDKWithUserId:self.userID nonce:self.nonce sign:self.sign appid:self.appid orderNo:self.orderNO apiVersion:@"1.0.0" licence: self.LICENCE faceType:type faceId:nil sdkConfig:config success:^{
//                [[WBFaceVerifyCustomerService sharedInstance] startWbFaceVeirifySdk];
//                [[Dialog Instance] hideHUD];
//
//            } failure:^(WBFaceError * _Nonnull error) {
//                [[Dialog Instance] hideHUD];
//                NSString *message = [NSString stringWithFormat:@"%@", error.desc];
//                NSLog(@"error: %@", error);
////                [ISMessages showCardAlertWithTitle:@"登录时候出错" message:message duration:10 hideOnSwipe:YES hideOnTap:YES alertType:ISAlertTypeInfo alertPosition:0 didHide:nil];
//            }];
//        });
//    }
//}
//
//// 上传到后台的图片, 需要先存储到硬盘中, 然后存储
//- (NSString *)base64String:(UIImage *)image {
//    image = [self zipScaleWithImage:image];
//    NSData *imageData = UIImageJPEGRepresentation(image, 0.9f);
//    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] ;
//    NSString *fileName = [filePath stringByAppendingFormat:@"/temp.jpeg"] ;
//    [imageData writeToFile:fileName atomically:YES] ;
//    NSData *data = [NSData dataWithContentsOfFile:fileName] ;
//    NSString *base64String = [NSString stringWithFormat:@"%@",
//                              [data base64EncodedStringWithOptions:0]];
//    NSFileManager *fileManager = [NSFileManager defaultManager] ;
//    if ([fileManager fileExistsAtPath:fileName]) {
//        [fileManager removeItemAtPath:filePath error:nil] ;
//    }
//    //+号必须替换为%2B，要不然同样会失败!
//    //    base64String = [base64String stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"] ;
//    return base64String ;
//}
//
//
//-(UIImage *)zipScaleWithImage:(UIImage *)sourceImage{
//    //进行图像尺寸的压缩
//    CGSize imageSize = sourceImage.size;//取出要压缩的image尺寸
//    CGFloat width = imageSize.width;    //图片宽度
//    CGFloat height = imageSize.height;  //图片高度
//
//
//    //1.宽高大于640(宽高比不按照2来算，按照1来算)
//    if (width > 640||height>640) {
//        if (width>height) {
//            CGFloat scale = height/width;
//            width = 640;
//            height = width*scale;
//        }else{
//            CGFloat scale = width/height;
//            height = 640;
//            width = height*scale;
//        }
//        //2.宽大于1280高小于1280
//    }else if(width>640||height<640){
//        CGFloat scale = height/width;
//        width = 640;
//        height = width*scale;
//        //3.宽小于1280高大于1280
//    }else if(width<640||height>640){
//        CGFloat scale = width/height;
//        height = 640;
//        width = height*scale;
//        //4.宽高都小于1280
//    }else{
//    }
//    //进行尺寸重绘
//    UIGraphicsBeginImageContext(CGSizeMake(width, height));
//    [sourceImage drawInRect:CGRectMake(0,0,width,height)];
//    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    return newImage;
//}
//

@end
